﻿using GMap.NET;
using System.Windows.Forms;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;

namespace LocationAwareness
{
    public class OSMMap : GMapControl
    {
        // marker
        GMapMarkerTransparentGoogleGreen currentMarker;
        GMapMarkerTransparentGoogleGreen poiMarker;

        // layers
        GMapOverlay top;
        GMapOverlay objects;
        GMapOverlay routes;
        GMapOverlay polygons;

        public OSMMap()
        {
            this.Height = 200;
            this.Width = 240;

            this.Manager.Mode = AccessMode.ServerAndCache;
            this.MapType = MapType.GoogleMap;
            this.MaxZoom = 17;
            this.MinZoom = 13;
            this.Zoom = 15;

            // set marker positions
            currentMarker = new GMapMarkerTransparentGoogleGreen(this.CurrentPosition);
  
            polygons = new GMapOverlay(this, "polygons");
            this.Overlays.Add(polygons);

            routes = new GMapOverlay(this, "routes");
            this.Overlays.Add(routes);

            objects = new GMapOverlay(this, "objects");
            this.Overlays.Add(objects);

            top = new GMapOverlay(this, "top");
            top.Markers.Add(currentMarker);
            top.Markers.Add(poiMarker);
            this.Overlays.Add(top);
        }

        public void updateMap(PointLatLng userPos, PointLatLng poiPos, double distance)
        {
            // set map center to middle of user position and POI position
            this.CurrentPosition = calculateCenter(userPos, poiPos);

            // reset zoom
            this.Zoom = calculateZoom(distance);

            // reset markers in map
            top.Markers.Clear();
            currentMarker = new GMapMarkerTransparentGoogleGreen(userPos);
            poiMarker = new GMapMarkerTransparentGoogleGreen(new PointLatLng(poiPos.Lat,poiPos.Lng));
            top.Markers.Add(currentMarker);
            top.Markers.Add(poiMarker);
            this.Overlays.Remove(top);
            this.Overlays.Add(top);

            //this.ReloadMap();
        }

        private PointLatLng calculateCenter(PointLatLng userPos, PointLatLng poiPos)
        {
            PointLatLng middle = new PointLatLng();

            middle.Lat = (userPos.Lat + poiPos.Lat) / 2;
            middle.Lng = (userPos.Lng + poiPos.Lng) / 2;

            return middle;
        }

        private int calculateZoom(double distance)
        {
            if (distance < 150)
                return 17;
            else if (distance < 250)
                return 16;
            else if (distance < 500)
                return 15;
            return 15;
        }
    }
} 

